<template>
  <el-button type="primary" @click="add" v-hasPermission="'user:add'">新增用户</el-button>
  <el-button type="danger" @click="batchDel" v-hasPermission="'user:delete'">批量删除</el-button>
  <el-table
      :data="userList"
      style="width: 100%"
      @selection-change="handleSelectionChange">

    <el-table-column type="selection" width="55"/>
    <el-table-column type="index" label="序号" width="60"/>
    <el-table-column property="loginAct" label="账号"/>
    <el-table-column property="name" label="姓名" show-overflow-tooltip/>
    <el-table-column property="phone" label="手机" show-overflow-tooltip/>
    <el-table-column property="email" label="邮箱" show-overflow-tooltip/>
    <el-table-column property="createTime" label="创建时间" show-overflow-tooltip/>
    <el-table-column label="操作" show-overflow-tooltip>
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)" v-hasPermission="'user:view'">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)" v-hasPermission="'user:edit'">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)" v-hasPermission="'user:delete'">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      background layout="prev, pager, next"
      :page-size = "pageSize"
      :total="total"
      @prev-click="toPage"
      @next-click="toPage"
      @current-change="toPage"/>

  <!-- 新增用户的对话框  -->
  <el-dialog v-model="userDialogVisible" :title="userQuery.id>0?'编辑用户':'新增用户'" center width="50%" draggable>

    <el-form ref="userRefForm" :model="userQuery" label-width="110px" :rules="userRules">
      <el-form-item label="账号" prop="loginAct">
        <el-input clearable v-model="userQuery.loginAct"/>
      </el-form-item>
      <!--  编辑    -->
      <el-form-item label="密码"  v-if="userQuery.id>0">
        <el-input type="password" show-password v-model="userQuery.loginPwd"/>
      </el-form-item>
      <!--  新增      -->
      <el-form-item label="密码" prop="loginPwd" v-else>
        <el-input type="password" show-password v-model="userQuery.loginPwd"/>
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input  clearable v-model="userQuery.name"/>
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input  clearable v-model="userQuery.phone"/>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input  clearable v-model="userQuery.email"/>
      </el-form-item>

      <el-form-item label="账号是否过期" prop="accountNoExpired">
        <el-select
            v-model="userQuery.accountNoExpired"
            placeholder="请选择"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="密码是否过期" prop="credentialsNoExpired">
        <el-select
            v-model="userQuery.credentialsNoExpired"
            placeholder="请选择"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否锁定" prop="accountNoLocked">
        <el-select
            v-model="userQuery.accountNoLocked"
            placeholder="请选择"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否可用" prop="accountEnabled">
        <el-select
            v-model="userQuery.accountEnabled"
            placeholder="请选择"
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

    </el-form>


    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="userSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip, removeToken} from "../util/util.js";

export default {
  name: "UserView",

  //注入父级页面 所有属性
  inject: ['reload'],

  data() {
    return {
      //用户列表list
      userList: [{}],
      total: 0,
      pageSize:0,
      userDialogVisible:false,
      userQuery:{},
      userRules:{
        loginAct: [
          {required: true, message: '请输入登录账号', trigger: 'blur'}
        ],
        loginPwd: [
          {required: true, message: '请输入登录密码', trigger: 'blur'},
          {min: 6, max: 16, message: '登录密码长度6-16位', trigger: 'blur'},
        ],
        name:[
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {pattern:/^[\u4e00-\u9fa5]+$/,message: '姓名必须全是中文', trigger: 'blur'},
        ],
        email:[
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {pattern:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,message: '格式错误', trigger: 'blur'},
        ],
        phone:[
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern:/^1[3456789]\d{9}$/,message: '手机号必须以数字1开头，第二位是3、4、5、6、7、8、9中的一个，后面跟着9个数字', trigger: 'blur'},
        ],
        accountNoExpired:[
          {required: true, message: '请选择', trigger: 'blur'},
        ],
        credentialsNoExpired:[
          {required: true, message: '请选择', trigger: 'blur'},
        ],
        accountNoLocked:[
          {required: true, message: '请选择', trigger: 'blur'},
        ],
        accountEnabled:[
          {required: true, message: '请选择', trigger: 'blur'},
        ],




      },
      //下拉选项
      options:[
        {
          label: '是',value:1
        },
        {
          label: '否',value:0
        }
      ],
      //定义用户id数组
      userIdArray:[],
    }
  },

  mounted() {
    this.getData(1);
  },

  methods: {
    //勾选或者取消勾选 触发该函数 selectionDataArray勾选的数据集合数组
    handleSelectionChange(selectionDataArray) {
      this.userIdArray = [];
      selectionDataArray.forEach(data => {
        let userId = data.id;
        this.userIdArray.push(userId);
      })
    },
    //查询用户列表
    getData(current) {
      doGet("/api/users", {
        current: current
      }).then((response) => {
        if (response.data.code === 200) {
          this.userList = response.data.data.list;
          this.total = response.data.data.total;
          this.pageSize = response.data.data.pageSize;
        }
      })
    },
    //分页函数 elementplus会自动向toPage传递当前页这个值
    toPage(current) {
      this.getData(current);
    },
    //详情
    view(id){
      //跳转到/dashboard/user/1路由
      this.$router.push("/dashboard/user/" + id);
    },
    //编辑
    edit(id){
      this.userDialogVisible = true;
      this.loadUser(id);
    },
    //加载用户信息
    loadUser(id){
      doGet("/api/user/"+id,{}).then((response)=>{
        if (response.data.code === 200){
          this.userQuery = response.data.data;
          this.userQuery.loginPwd = "";
        }
      })
    },

    add(){
      this.userQuery = {};
      this.userDialogVisible = true;
    },

    userSubmit(){
      let formData = new FormData();
      for (let field in this.userQuery){
        formData.append(field,this.userQuery[field]);
      }
      this.$refs.userRefForm.validate((isValid) =>{
        if (isValid){
          if (this.userQuery.id > 0){
            //编辑
            doPut("/api/user",formData).then(response=>{
              console.log(response);
              if (response.data.code === 200){
                messageTip("编辑用户成功！","success");
                //页面刷新
                this.reload();
              }else {
                messageTip("编辑用户失败！","error");
                console.log(response);
              }
            })
          }else {
            doPost("/api/user",formData).then(response=>{
              console.log(response);
              if (response.data.code === 200){
                messageTip("新增用户成功！","success");
                //页面刷新
                this.reload();
              }else {
                messageTip("新增用户失败！","error");
                console.log(response);
              }
            })
          }
        }
      })
    },
    //删除用户
    del(id){
      messageConfirm("您确定要删除该数据吗？")
          .then(() => {
            doDelete("/api/user/"+id,{}).then((response)=>{
              if (response.data.code === 200){
                messageTip("删除成功!","success");
                //页面刷新
                this.reload();
              }else {
                messageTip("删除失败,原因:"+response.data.msg,"error");
              }
            })
          }).catch(() => {
        messageTip("取消删除!","warning");
      })
    },
    //批量删除
    batchDel(){
      if (this.userIdArray.length <= 0){
        messageTip("请选择要删除的数据!","warning");
        return;
      }else {
        messageConfirm("您确定要删除这些数据吗？")
            .then(() => {
              //[1,3,5,7] => "1,3,5,7" 数组转字符串
              let ids = this.userIdArray.join(",");
              doDelete("/api/user/",{
                ids
              }).then(response=>{
                if (response.data.code === 200){
                  messageTip("批量删除成功!","success");
                  //页面刷新
                  this.reload();
                }else {
                  messageTip("批量删除失败,原因:"+response.data.msg,"error");
                }
              })
            }).catch(() => {
          messageTip("取消删除!","warning");
        })
      }
    },
  }

}
</script>

<style scoped>
.el-pagination{
  margin-top: 10px;
}
.el-table{
  margin-top: 10px;
}
.el-select{
  width: 100%;
}
</style>